/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/lowest-common-ancestor
   @Language: C++
   @Datetime: 16-02-09 05:58
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

// Method 1, recursion, Time O(n), Space O(1), Time 472ms
class Solution {
public:
	/*
	 * @param root: The root of the binary search tree.
	 * @param A: A TreeNode in a Binary.
	 * @param B: A TreeNode in a Binary.
	 * @return: Return the least common ancestor(LCA) of the two nodes.
	 */
	TreeNode * lowestCommonAncestor(TreeNode * root, TreeNode * A, TreeNode * B) {
		// write your code here
		if(root==NULL || root==A || root==B) return root;
		TreeNode *left=lowestCommonAncestor(root->left,A,B);
		TreeNode *right=lowestCommonAncestor(root->right,A,B);
		if(left && right) return root;
		return left?left:right;
	}
};

// Method 2, Pre-Order path, Time O(n), Space O(h), Time 112ms
class Solution {
	bool lca(TreeNode *root, TreeNode *node, deque<TreeNode*> &q){
		q.push_back(root);
		if(root==NULL) return false;
		if(root==node) return true;
		if(lca(root->left,node,q)) return true;
		q.pop_back();
		if(lca(root->right,node,q)) return true;
		q.pop_back();
		return false;
	}
public:
	/*
	 * @param root: The root of the binary search tree.
	 * @param A: A TreeNode in a Binary.
	 * @param B: A TreeNode in a Binary.
	 * @return: Return the least common ancestor(LCA) of the two nodes.
	 */
	TreeNode * lowestCommonAncestor(TreeNode * root, TreeNode * A, TreeNode * B) {
		// write your code here
		deque<TreeNode*> qa, qb;
		lca(root,A,qa);
		lca(root,B,qb);
		for(; qa.size() && qb.size() && qa.front()==qb.front(); qa.pop_front(),qb.pop_front())
			if(qa.front()!=NULL) root=qa.front();
		return root;
	}
};
